/** 
 * @author hannz
 * content:article
 * creatTime:2023年7月17日16:37:32
  */
const article = require('../db/model/article')
const ArticleCate = require('../db/model/articleCate')
const user = require('../db/model/user')
const express = require("express");
const router = express.Router();
const { check, body, validationResult } = require('express-validator')
/**
 * @swagger
 * /api/article/getAllArticles:
 *   get:
 *     tags:
 *       - 文章
 *     description: 获取文章
 *     security:
 *      - CoreAPI: []        
 *     responses:
 *       200:
 *         description: 获取成功
 *
 */
router.get('/getAllArticles', (req, res) => {
    article.findAll({
        attributes: ['id', 'title', 'category', 'author', 'updatedAt']
    }).then(data => {
        res.json({
            status: 200,
            message: '',
            data
        })
    })
})

/**
 * @swagger
 * /api/article/addArticle:
 *   post:
 *     tags:
 *       - 文章
 *     description: 添加文章
 *     security:
 *      - CoreAPI: []
 *     consumes:
 *     - "application/json"
 *     requestBody:
 *       required: true
 *       content:
 *          application/json:
 *              schema:
 *                  type: object
 *                  properties:
 *                      title:
 *                          type:string
 *                          description:文章标题
 *                      articleCateId:
 *                          type:number
 *                          description:分类id
 *                      content:
 *                          type:string
 *                          description:内容
 *                      userId:
 *                          type:number
 *                          description:作者id
 *                      
 *              example:        #请求参数样例。
 *                      title: a
 *                      articleCateId: 1
 *                      content: test
 *                      userId: 1
 *                          
 *     responses:
 *       200:
 *         description: 添加成功
 *
 */
router.post('/addArticle', [
    body('title').notEmpty().withMessage('标题不能为空'),
    body('articleCateId').notEmpty().withMessage('分类不能为空'),
    body('content').notEmpty().withMessage('内容不能为空'),
    body('userId').notEmpty().withMessage('错误的作者'),
], async (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.json({
            status: 405,
            message: '请检查参数是否合法！',
            data: errors.array()
        })
    }
    const { articleCateId, title, content, userId } = req.body
    const articleCate = await ArticleCate.findByPk(articleCateId);
    const articleCateName = articleCate.cateName;
    const userRes = await user.findByPk(userId);
    const articleRes = await article.create({
        title: title,
        content: content,
        category: articleCateName,
        articleCateId: articleCateId,
        userId,
        author: userRes.userName,
        like: 0,
        watch: 0
    });
    res.json({
        status: 200,
        data: articleRes,
        message: '添加成功！',
    })
    /*     if (articleCate && userRes) {
            const articleCateName = articleCate.cateName;
            // 创建 Article，并设置 cateName 属性为 articleCateName
            const articleRes = await article.create({
                title: title,
                content: content,
                category: articleCateName,
                articleCateId: articleCateId,
                userId,
                author: userRes.userName,
                like: 0,
                watch: 0
            });
            if (articleRes) {
                res.json({
                    status: 200,
                    message: '添加成功！',
                })
            } else {
                res.json({
                    status: 403,
                    message: '添加失败！',
                })
            }
    
        } else {
            res.json({
                status: 403,
                message: '添加失败！' + ` 分类不存在。`,
            })
        } */
})

/**
 * @swagger
 * /api/article/delArticle:
 *   post:
 *     tags:
 *       - 文章
 *     description: 删除文章
 *     security:
 *      - CoreAPI: []
 *     consumes:
 *     - "application/json"
 *     requestBody:
 *       required: true
 *       content:
 *          application/json:
 *              schema:
 *                  type: object
 *                  properties:
 *                      id:
 *                          type:number
 *                          description:id
 *                      
 *              example:        #请求参数样例。
 *                      id: 
 *                          
 *     responses:
 *       200:
 *         description: 删除成功
 *
 */
router.post('/delArticle', [
    check('id', '文章id不能为空').notEmpty(),
], (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.json({
            status: 405,
            message: '请检查参数是否合法！',
            data: errors.array()
        })
    }
    const { id } = req.body
    article.findByPk(id).then(data => {
        if (data != null) {
            article.destroy({
                where: {
                    id
                }
            })
                .then(data2 => {
                    res.json({
                        status: 200,
                        message: '删除成功！',
                    })
                })
        } else {
            res.json({
                status: 403,
                message: 'id错误',
            })
        }
    })
})

/**
 * @swagger
 * /api/article/editArticle:
 *   post:
 *     tags:
 *       - 文章
 *     description: 修改文章
 *     security:
 *      - CoreAPI: []
 *     consumes:
 *     - "application/json"
 *     requestBody:
 *       required: true
 *       content:
 *          application/json:
 *              schema:
 *                  type: object
 *                  properties:
 *                      title:
 *                          type:string
 *                          description:文章标题
 *                      id:
 *                          type:number
 *                          description:文章id
 *                      content:
 *                          type:string
 *                          description:文章内容
 *                      articleCateId:
 *                          type:string
 *                          description:分类id
 *                      
 *              example:        #请求参数样例。
 *                      title: test2
 *                      id: 1
 *                      content: 123
 *                      articleCateId: 1
 *              
 *                          
 *     responses:
 *       200:
 *         description: 修改成功
 *
 */
router.post('/editArticle', [
    body('title').notEmpty().withMessage('标题不能为空'),
    body('articleCateId').notEmpty().withMessage('分类不能为空'),
    body('content').notEmpty().withMessage('内容不能为空'),
], (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.json({
            status: 405,
            message: '请检查参数是否合法！',
            data: errors.array()
        })
    }

    const { id, content, articleCateId, title } = req.body
    ArticleCate.findByPk(articleCateId).then(cate => {
        console.log(cate);
        const category = cate.cateName
        article.findByPk(id)
            .then(data => {
                if (data != null) {
                    article.update({ content, articleCateId, title, category }, {
                        where: {
                            id
                        }
                    })
                        .then(data2 => {
                            res.json({
                                status: 200,
                                message: '修改成功！',
                            })
                        })
                } else {
                    res.json({
                        status: 403,
                        message: 'id错误',
                    })
                }
            })
    })

})

/**
 * @swagger
 * /api/article/getArticleById:
 *   get:
 *     tags:
 *       - 文章
 *     description: 通过id获取文章
 *     security:
 *      - CoreAPI: []
 *     parameters:
 *            - name: id 
 *              in: query
 *              description: 文章id
 *              required: true
 *              schema:
 *                  type: string
 *                  default: null               
 *     responses:
 *       200:
 *         description: success
 *
 */
router.get('/getArticleById', (req, res) => {
    const { id } = req.query
    article.findByPk(id)
        .then(data => {
            console.log(data);
            res.json({
                status: 200,
                data,
                message: 'success',

            })
        }).catch(err => {
            res.json({
                status: 403,
                message: '系统错误',

            })
        })

})
module.exports = router